package cn.nexttec.noteplayer.common

import android.content.Context
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.LifecycleOwner
import androidx.activity.result.ActivityResultRegistryOwner

class SubtitlePicker(
    private val context: Context,
    lifecycleOwner: LifecycleOwner,
    private val onSubtitlePicked: (uri: Uri) -> Unit
) {
    private lateinit var launcher: ActivityResultLauncher<Array<String>>

    init {
        // 注册 Launcher
        if (context is ActivityResultRegistryOwner) {
            launcher = context.activityResultRegistry.register(
                "subtitle_picker",
                lifecycleOwner,
                ActivityResultContracts.OpenDocument()
            ) { uri: Uri? ->
                uri?.let { onSubtitlePicked(it) }
            }
        } else {
            throw IllegalArgumentException("Context 必须实现 ActivityResultRegistryOwner（如 AppCompatActivity）")
        }
    }

    fun pick() {
        val mimeTypes = arrayOf(
            "application/x-subrip", // .srt
            "text/vtt",             // .vtt
            "text/plain"            // 某些 .srt 文件被系统识别为 text/plain
        )
        launcher.launch(mimeTypes)
    }
}
